package com.atnjupt.controller;

import com.atnjupt.bean.Book;
import com.atnjupt.controller.utils.Result;
import com.atnjupt.service.IBookService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/books")
public class BookController2 {
    @Autowired
    IBookService iBookService;

    @GetMapping("/{id}")
    public Result getBookById(@PathVariable("id") Integer id) {
        Book getBook = iBookService.getById(id);
        Boolean flag = null;
        if (getBook != null) {
            flag = true;
        } else {
            flag = false;
        }
        Result result = new Result(flag, getBook);
        return result;
    }

    @GetMapping
    public Result getAllBooks() {
        List<Book> list = iBookService.list();
        Boolean flag = null;
        if (list != null) {
            flag = true;
        } else {
            flag = false;
        }
        Result result = new Result(flag, list);
        return result;
    }

    @PostMapping
    public Result addBook(@RequestBody Book book) throws IOException {
        if (book.getName().equals("aaa")) {
            throw new IOException();
        }
        Boolean flag = iBookService.saveBook(book);
        Result result = new Result(flag, flag ? "添加成功" : "添加失败");
        return result;
    }

    @PutMapping
    public Result updateBook(@RequestBody Book book) {
        Result result = new Result(iBookService.modify(book));
        return result;
    }

    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable("id") Integer id) {
        // 得到删除标志
        Boolean flag = iBookService.deleteBookById(id);
        // 封装数据
        Result result = new Result(flag);
        return result;
    }

    //    @GetMapping("/{currentPage}/{pageSize}")
//    public Result getPages(@PathVariable("currentPage") Integer currentPage, @PathVariable("pageSize") Integer pageSize) {
//        IPage<Book> page = iBookService.getPage(currentPage, pageSize);
//        if (currentPage > page.getPages()){
//            //如果当前页码已经大于总页码就，按照最大页码来查询
//           page = iBookService.getPage((int)page.getPages(),pageSize);
//        }
//        Result result = new Result(null != page,page);
//        return result;
//    }
    @GetMapping("/{currentPage}/{pageSize}")
    public Result getPages(@PathVariable("currentPage") Integer currentPage, @PathVariable("pageSize") Integer pageSize,Book book) {
//        System.out.println("=====>" + book);
        IPage<Book> page = iBookService.getPage(currentPage, pageSize,book);
        if (currentPage > page.getPages()) {
            //如果当前页码已经大于总页码就，按照最大页码来查询
            page = iBookService.getPage((int) page.getPages(), pageSize,book);
        }
        Result result = new Result(null != page, page);
        return result;
    }
}
